<template>
  <div class="formBox">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="loginForm"
    >
      <el-form-item class="title">
        <h2>注册</h2>
        <p>已有帐号，请<a href="/#/Login">登录</a></p>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="ruleForm.confirmPassword"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped>
a {
  text-decoration: none;
}
.formBox {
  border-radius: 10px;
  background-color: #fff;
  padding: 15% 15% 15% 5%;
}
.title h2,
p {
  margin: 0%;
  padding: 0%;
}
.title h2 {
  color: rgb(12, 8, 8);
  font-size: xx-large;
}
</style>
<script>
export default {
  data() {
    return {
      ruleForm: {
        userName: "", //用户名
        password: "", //密码
        confirmPassword: "", //确认密码
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 4, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          { min: 4, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          // 验证通过，执行action Register
            
           var result=await this.$store.dispatch("Register",this.ruleForm)
           if(result){
            //    登陆成功,弹出提示，执行路由跳转
            this.$message.success("注册成功，即将跳转到个人页面~~~")
            
            var that=this;

            window.setTimeout(function(){
                that.$router.push('/User')
            },1000)
           }
           else{
               this.$message.error("服务器错误，注册失败！");
               this.ruleForm.password="";
           }
        } else {
          this.$message.error("您的输入有误");
          this.resetForm(formName);
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>